import pickle
from datetime import datetime

import numpy as np
from flask import Flask, request, jsonify

app = Flask(__name__)
# 读取文件
question_dict = np.load('data/file_new.npy', allow_pickle=True).item()
# 前端拿的题目与答案
# 当前时间
current_time = datetime.now()

# 格式化时间字符串，精确到分钟
time_str = current_time.strftime("%Y-%m-%d")

# 将字典写入 pickle 文件
file_name = f"data/data_{time_str}.pkl"

# 读取 pickle 文件
with open("data/test_data.pkl", 'rb') as f:
    update_dict = pickle.load(f)

@app.route('/123')
def hello_world():  # put application's code here
    return 'Hello World!'


@app.route('/get_answer', methods=['POST'])
def taxApi():
    if request.method == 'POST':
        # 获取 POST 请求体中的 JSON 数据
        data = request.json

        # 在这里处理你的数据
        request_data = data.get('test', '')

        res = []
        mymap = {"0": "A", "1": "B", "2": "C", "3": "D", "4": "E", "5": "F", "6": "G", 'no': '无答案'}
        flag = True
        for i in request_data:
            if i in question_dict:
                temp = question_dict[i].split(",")
                flag = True
            else:
                #在前端题库查找,不需要映射
                flag = False
                temp = find_answer(i)
            if flag:
                tmp_res = []
                for label in temp:
                    tmp_res.append(mymap[label])
                res.append(tmp_res)
            else:
                res.append(temp)
        response_data = {}
        for i in res:
            response_data["answer"] = i
        # 返回处理后的结果
        return response_data, 200

    else:
        # 如果不是 POST 请求，则返回错误信息
        return jsonify({'error': 'Only POST requests are allowed'}), 405
@app.route('/save_data', methods=['POST'])
def save_data():
    data = request.json  # 获取发送过来的 JSON 数据
    # QA = data.get('QA', '')
    # 在这里可以将数据存储到数据库或进行其他处理
    # print(QA)
    # print(type(QA))
    # 当前时间
    current_time = datetime.now()

    # 格式化时间字符串，精确到分钟
    time_str = current_time.strftime("%Y-%m-%d")

    # 将字典写入 pickle 文件
    file_name = f"data/data_{time_str}.pkl"
    with open(file_name, 'wb') as f:
        pickle.dump(data, f)
    print(data)  # 打印接收到的数据
    print(type(data))
    # 读取 pickle 文件
    with open(file_name, 'rb') as f:
        loaded_data = pickle.load(f)

    # 输出加载的数据
    print("加载的数据:", loaded_data)
    print()
    return 'Data received successfully!'


def find_answer(question):
    if question in update_dict:
        return [update_dict[question]]
    else:
        return ["no_answer"]

if __name__ == '__main__':
    app.run(host='0.0.0.0', port='5000')
